package cn.topcodes.tcsf.admin.commons.messagesource;

import cn.topcode.unicorn.utils.StringUtil;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.w3c.dom.Element;
import java.util.HashSet;
import java.util.Set;

/**
 * @author unicorn
 */
public class MessageSourceBeanDefinitionParser implements BeanDefinitionParser {

    private Set<String> basenames = new HashSet<String>();

    private ReloadableResourceBundleMessageSource messageSource;

    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        String basename = element.getAttribute("basename");
        if(StringUtil.isBlank(basename)) {
            return null;
        }
        basenames.add(basename);

        BeanDefinition beanDefinition = null;
        try {
            beanDefinition = parserContext.getRegistry().getBeanDefinition("messageSource");
        }catch (Exception e) {}
        if(beanDefinition == null) {
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ReloadableResourceBundleMessageSource.class);
            beanDefinition = builder.getBeanDefinition();
            beanDefinition.getPropertyValues().add("useCodeAsDefaultMessage", true);
            beanDefinition.getPropertyValues().add("cacheSeconds", 1800);
            parserContext.getRegistry().registerBeanDefinition("messageSource", beanDefinition);
        }else {
            beanDefinition.getPropertyValues().removePropertyValue("basenames");
            beanDefinition.getPropertyValues().addPropertyValue("basenames", basenames);
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
        }
        return beanDefinition;
    }

}
